from http_factory import HttpClientFactory
import asyncio
import time
import sys

# 同步请求测试
def test_sync(count=10):
    client = HttpClientFactory.create(
        async_mode=False,
        base_url='http://localhost:8000'
    )
    
    start_time = time.time()
    
    for i in range(count):
        try:
            response = client.get('/health')
            print(f"同步请求 {i+1}/{count} 完成")
        except Exception as e:
            print(f"请求失败: {str(e)}")
    
    total_time = time.time() - start_time
    print(f"\n同步请求完成 {count} 次请求，耗时: {total_time:.2f}秒，平均: {total_time/count:.2f}秒/请求")
    return total_time

# 异步请求测试
async def test_async(count=10):
    client = HttpClientFactory.create(
        async_mode=True,
        base_url='http://localhost:8000'
    )
    
    start_time = time.time()
    
    # 创建所有任务
    tasks = []
    for i in range(count):
        tasks.append(client.get('/health'))
    
    # 等待所有任务完成
    results = await asyncio.gather(*tasks, return_exceptions=True)
    
    for i, result in enumerate(results):
        if isinstance(result, Exception):
            print(f"异步请求 {i+1}/{count} 失败: {str(result)}")
        else:
            print(f"异步请求 {i+1}/{count} 完成")
    
    total_time = time.time() - start_time
    print(f"\n异步请求完成 {count} 次请求，耗时: {total_time:.2f}秒，平均: {total_time/count:.2f}秒/请求")
    return total_time

if __name__ == '__main__':
    # 获取请求次数参数
    count = 10
    if len(sys.argv) > 1:
        count = int(sys.argv[1])
    
    print(f"开始测试: {count} 次请求\n")
    
    # 运行同步测试
    print("=== 同步请求测试 ===")
    sync_time = test_sync(count)
    
    print("\n=== 异步请求测试 ===")
    async_time = asyncio.run(test_async(count))
    
    # 比较结果
    print("\n=== 性能比较 ===")
    speedup = sync_time / async_time
    print(f"同步总耗时: {sync_time:.2f}秒")
    print(f"异步总耗时: {async_time:.2f}秒")
    print(f"性能提升: {speedup:.2f}倍") 